<?php
class CompressCacheService
{
	public function getCacheDirById($id)
	{
		if(strlen($id)<9)
		{
			$id	= sprintf("%09s",$id);
		}
		return substr($id,0,3).DIRECTORY_SEPARATOR.substr($id,3,3).DIRECTORY_SEPARATOR.substr($id,6,3).DIRECTORY_SEPARATOR;
	}
	
	public function getCacheData($base, $cacheDir, $id)
	{
		$filePath	= $base.$cacheDir.$id;
		if(!is_file($filePath))
		{
			return false;
		}
		$fh			= fopen($filePath,'r');
		if(!$fh)
		{
			return false;
		}
		$content		= fread($fh,filesize($filePath));
		if($content!==false)
		{
			$content	= unserialize($content);
		}
		fclose($fh);
		return $content;
	}
	
	public function setCacheData($base, $cacheDir, $id, $data)
	{
		$filePath	= $base.$cacheDir.$id;
		$d			= dirname($filePath);
    	if(!is_dir($d))
    	{
    		mkdir($d,0777,true);
    	}
		$fp 		= fopen($filePath, "w");
		if(flock($fp, LOCK_EX))
		{
		    fwrite($fp, serialize($data));
		    flock($fp, LOCK_UN);
		}
		fclose($fp);
	}
	
	public function delCacheData($base, $cacheDir, $id)
	{
		$filePath	= $base.$cacheDir.$id;
		if(!is_file($filePath))
		{
			return false;
		}
		
		$result	= unlink($filePath);
		
		$d	= dirname($filePath);
		while($this->isEmptyDir($d))
		{
			rmdir($d);
			$d		= dirname($d);
		}
		return $result;
	}
	
	private function isEmptyDir($d)
	{
		$handle 	= opendir($d);
		while (($file = readdir($handle)) !== false)
		{  
			if ($file != "." && $file != "..")
			{  
				closedir($handle);
				return false;
			}
		}
		closedir($handle);
		return true;
	}
}
?>